<!DOCTYPE html>
<html lang="en">
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>关爱健康</title>
    <meta name="description" content="关爱健康">
    <meta name="keywords" content="关爱健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <link rel="shortcut icon" href="../img/favicon.ico">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <!-- 引入组件库 -->
    <script type="text/javascript" src="../js/jquery.min.js"></script>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript" src="../plugins/elementui/index.js"></script>
    <script type="text/javascript" src="../js/axios-0.18.0.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=aY6dLuYG2LQyabUW0VZ3MqfZkuGhuy5M">
    </script>

    <style>
        /*两个百度地图的大小*/
        #container {
            height: 680px;
            /*height: auto;*/
        }

        #allmap {
            width: auto;
            height: 330px;
            font-family: "微软雅黑";
            border: 3px solid lightyellow;
        }

        /*去掉百度地图的logo*/
        .BMap_cpyCtrl {
            display: none;
        }

        .anchorBL {
            display: none;
        }

        .tangram-suggestion-main {
            z-index: 9999999999;
        }
    </style>
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>首页
            <small>公司分布图</small>
        </h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>公司分布图</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="app-container">
        <div class="box">
            <el-tabs v-model="activeName" type="card">
                <el-tab-pane label="分布图" name="first">
                    <div id="container"></div>
                </el-tab-pane>
                <el-tab-pane label="详细信息" name="second">
                    <div class="filter-container">
                        <el-input placeholder="公司地址" v-model="pagination.queryString" style="width: 200px;"
                                  class="filter-item"></el-input>
                        <el-button @click="search()" class="dalfBut">查询</el-button>
                        <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
                    </div>
                    <el-table size="small" current-row-key="id" :data="dataList" border stripe highlight-current-row>
                        <el-table-column type="index" align="center" label="序号"></el-table-column>
                        <el-table-column prop="companyAddress" label="公司地址" align="center"></el-table-column>
                        <el-table-column prop="longitude" label="所在经度" align="center"></el-table-column>
                        <el-table-column prop="latitude" label="所在纬度" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                class="pagiantion"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="pagination.currentPage"
                                :page-sizes="[10, 20, 30, 40, 50]"
                                :page-size="pagination.pageSize"
                                layout="total,sizes, prev, pager, next, jumper"
                                :total="pagination.total">
                        </el-pagination>
                    </div>

                    <!-- 新增地址弹层 -->
                    <div class="add-form">
                        <el-dialog title="新增地址" :visible.sync="dialogFormVisible" v-if="dialogFormVisible">
                            <el-form ref="dataAddForm" :model="formData" label-position="right" label-width="1px">
                                <el-form-item>
                                    <!--<input type="text" id="suggestId" size="20" style="width:150px;"/>-->
                                    <el-input type="text" id="suggestId" name="address_detail" placeholder="地址"
                                              v-model="address_detail"></el-input>
                                </el-form-item>
                            </el-form>
                            <div id="allmap">
                            </div>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button @click="resetForm('dataAddForm')">重置</el-button>
                                <el-button type="primary" @click="handleAdd()">确定</el-button>
                            </div>
                        </el-dialog>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</div>

</body>

<script type="text/javascript">
    const vue = new Vue({
        el: '#app',
        data: {
            activeName: 'first',        // 添加/编辑窗口Tab标签名称
            pagination: {               // 分页相关属性
                currentPage: 1,
                pageSize: 10,
                total: 0,
                queryString: null,
            },
            dataList: [],               // 列表数据
            address_detail: null,       //详细地址
            userlocation: {lng: "", lat: ""},
            dialogFormVisible: false    // 控制添加窗口显示/隐藏
        },
        //created:在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图。
        //mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
        mounted() {
            this.getNewMapData();
        },
        created() {
            this.findPage();
        },
        methods: {
            showMessage(r) {
                if (r == 'Error: Request failed with status code 403') {
                    //权限不足
                    this.$message.error('无访问权限');
                    return;
                } else {
                    this.$message.error('未知错误');
                    return;
                }
            },
            //初始化地图数据
            getNewMapData() {
                // 设置元素内容为百度地址
                var map = new BMap.Map("container");            // 创建地图实例
                var point = new BMap.Point(114.400, 30.530);    // 创建点坐标
                map.centerAndZoom(point, 13);                   // 初始化地图，设置中心点坐标和地图级别
                map.enableScrollWheelZoom();                    //启动鼠标滚轮缩放地图
                map.setMapStyle({style: 'light'});

                // 创建地图中的标记 标记对应的地址文本
                var icon = new BMap.Icon('http://api.map.baidu.com/img/markers.png', new BMap.Size(21, 25), {anchor: new BMap.Size(10, 30)});

                // 发现ajax请求   获取公司地址的详细信息   地址名称, 经纬度
                axios.get("/map/getAddressDetail.do").then((res) => {
                    if (res.data.flag) {
                        var mkr, label;
                        res.data.data.forEach(add_deail => {
                            mkr = new BMap.Marker(new BMap.Point(add_deail.longitude, add_deail.latitude), {icon: icon});
                            label = new BMap.Label(add_deail.companyAddress, {offset: new BMap.Size(20, -10)});
                            mkr.setLabel(label);        // 设置标注的文本内容
                            map.addOverlay(mkr);        // 将覆盖物添加到地图中
                        });
                    } else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            //查询按钮
            search() {
                this.pagination.currentPage = 1;
                this.findPage();
            },
            // 初始页currentPage、初始每页数据数pagesize和数据data
            handleSizeChange(size) {
                this.pagination.pageSize = size;
                this.findPage();
            },
            //切换页码
            handleCurrentChange(currentPage) {
                this.pagination.currentPage = currentPage;
                this.findPage();
            },
            //分页查询
            findPage() {
                var param = {
                    currentPage: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    queryString: this.pagination.queryString
                };
                axios.post("/map/findPage.do", param).then((res) => {
                    // 解析响应回来的数据  为模型数据赋值
                    this.pagination.total = res.data.total;
                    this.dataList = res.data.rows;
                });
            },
            //添加
            handleAdd() {
                this.$confirm("你确定要添加当前该地址为公司新地址吗？", "提示", {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {                   // 点击确认按钮  发送ajax请求
                    var param = {
                        // companyAddress: this.address_detail,
                        companyAddress: $("#suggestId").val(),
                        longitude: this.userlocation.lng,
                        latitude: this.userlocation.lat
                    };

                    // 发送一个ajax请求，添加一个新地址
                    axios.post("/map/add.do", param).then((res) => {
                        //关闭新增窗口
                        this.dialogFormVisible = false;
                        if (res.data.flag) { // 服务器端处理成功
                            this.findPage();
                            //弹出提示信息
                            this.$message.success(res.data.message);
                            this.getNewMapData();
                        } else {// 服务器端处理失败
                            this.$message.error(res.data.message);
                        }
                    }).catch((res) => {
                        this.showMessage(res);
                    });
                })
            },
            // 删除
            handleDelete(row) {
                //  row其实是一个json对象 dataList
                this.$confirm("此操作将永久删除地址？", "提示", {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {                   // 点击确认按钮  发送ajax请求
                    axios.delete("/map/delete.do?id=" + row.id).then((res) => {
                        if (res.data.flag) {
                            this.$message.success(res.data.message);
                            this.findPage();    // 删除成功后 重新分页查询
                            this.getNewMapData();
                        } else {                  // 删除数据失败
                            this.$message.error(res.data.message);
                        }
                    }).catch((res) => {
                        this.showMessage(res);
                    });
                }).catch(() => {                  // 点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '操作已取消'
                    });
                })
            },
            // 重置表单
            resetForm(formName) {
                this.formData = {};//重置数据
                this.address_detail = null;
            },
            // 显示新增图片的dialog
            handleCreate() {
                this.dialogFormVisible = true;
                this.resetForm('dataAddForm');

                this.$nextTick(() => {
                    const th = this;
                    // 创建Map实例
                    var map = new BMap.Map("allmap");
                    // 初始化地图,设置中心点坐标，
                    var point = new BMap.Point(114.400, 30.530); // 创建点坐标
                    map.centerAndZoom(point, 13);
                    map.enableScrollWheelZoom();
                    map.setMapStyle({style: 'light'});

                    //建立一个自动完成的对象
                    var ac = new BMap.Autocomplete({
                        "input": "suggestId"
                        , "location": map
                    });

                    var myValue;
                    ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                        var _value = e.item.value;
                        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                        this.address_detail = myValue
                        setPlace();
                    });

                    function setPlace() {
                        map.clearOverlays();    //清除地图上所有覆盖物
                        function myFun() {
                            th.userlocation = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                            map.centerAndZoom(th.userlocation, 18);
                            map.addOverlay(new BMap.Marker(th.userlocation));    //添加标注
                            //console.log(local.getResults())
                            //console.log(local.getResults()["keyword"])
                        }

                        var local = new BMap.LocalSearch(map, { //智能搜索
                            onSearchComplete: myFun
                        });
                        local.search(myValue);

                        /*//测试输出坐标（指的是输入框最后确定地点的经纬度）
                        map.addEventListener("click", function (e) {
                            //经度
                            console.log(th.userlocation.lng);
                            //维度
                            console.log(th.userlocation.lat);
                        })*/
                    }
                });

            }
        }
    });
</script>
</html>